<?php
namespace app\web\controller;

use app\web\model\Admin as adminM;
use think\Db;
use think\Request;
use app\common\controller\commonApi as comm;

/**
 * Class Admin
 * @package app\web\controller
 * by J.sky
 * 2020年5月5日11:05
 */
class Admin
{
    /**
     * 登录
     * @return string
     */
    public function login()
    {
        try {
            //赋值
            $username = input('post.username', '', 'trim');
            $password = input('post.password', '', 'trim');

            //逻辑判断
            //获取输入账户的信息
            $adminInfo = adminM::where('username', $username)->find();

            //判断账户是否存在
            if (empty($adminInfo)) {
                ret(400, '账户不存在');
            }

            //判断密码是否正确
            if (!password_verify($password, $adminInfo->password)) {
                ret(400, '密码不正确');
            }

            $retData = array();
            //获取返回信息
            $retData['token'] = randomStr(64, 3) . $adminInfo->id;
            $retData['nike'] = $adminInfo->nike;
            $retData['username'] = $adminInfo->username;
            $outTime = time() + (3600 * 3);
            $outTimeDate = date('Y-m-d H:i:s', $outTime); //有效时间
            if (adminM::where('id', $adminInfo->id)->update(['token' => $retData['token'], 'out_time' => $outTimeDate]) !== false) {
                comm::oplog("用户登陆", $adminInfo->id, $username, "登录成功,帐号:" . $username . ",操作用户IP:" . get_ip());
                //判断是否是超级用户
                $menuArr = Db::name("group")->field('menu,home')->where('id', $adminInfo->group_id)->find();
                if ($menuArr['menu'] == '0') {
                    $menuList = Db::name("menu")->order('sort', 'desc')->select();
                } else {
                    $menuList = Db::name("menu")->where(['id' => explode(",", $menuArr['menu'])])->order('sort', 'desc')->select();
                }
                $retData['home'] = $menuArr['home'];
                $retData['menu'] = getChild($menuList);
                $meunArr = array_column($menuList, 'key');
                $menuList = [];
                foreach ($meunArr as $item) {
                    $menuList[] = '/' . $item;
                }
                $retData['menuList'] = $menuList;
                ret(200, '成功', $retData);
            }
        } catch (\Exception $e) {
            comm::oplog("sql错误", $adminInfo->id, $adminInfo->username, json_encode(['错误API' => retMAC(), 'error' => $e->getMessage(), '操作用户IP' => get_ip()]));
            rLog(['operate' => 'sql错误', 'error' => $e->getMessage()]);
            ret(404, '服务器异常请联系管理员');
        }
    }

    /**
     * 新增管理员
     * @return mixed
     */
    public function register(Request $request)
    {
        try {
            //获取管理员信息
            $adminInfo = $request->adminInfo;

            //逻辑判断
            $data['username'] = input('post.username', '', 'trim');
            empty($data['username']) ? ret(400, '请输入账户名称！') : '';
            $pwd = input('post.password');
            empty($pwd) ? ret(400, '请填写账户密码！') : '';
            $newPwd = input('post.confirm_password');
            empty($newPwd) ? ret(400, '请填写确认账户密码！') : '';
            if ($pwd != $newPwd) {
                ret(400, '两次密码不一致！');
            }
            $data['password'] = password_hash($pwd, PASSWORD_DEFAULT);
            $ret = adminM::where('username', $data['username'])->field('id')->find();
            if ($ret) {
                ret(400, '用户名已存在！');
            }

            $g_id = input('post.group_id', '', 'trim');
            empty($g_id) ? ret(400, '请选择所属分组！') : '';
            $data['group_id'] = $g_id;

            $data['nike'] = empty(input('post.nike', '', 'trim')) ? $data['username'] : input('post.nike', '', 'trim');
            $data['out_time'] = date('Y-m-d H:i:s', time());

            $addRte = adminM::create($data);
            if ($addRte !== false) {
                comm::oplog("新增管理员", $adminInfo['id'], $adminInfo['username'], "新增账户ID:" . $addRte->id . " | 新增账户:" . $addRte->username . " | 操作用户IP:" . get_ip());
                ret(200, '成功');
            }
            ret(400, '注册失败');
        } catch (\Exception $e) {
            comm::oplog("sql错误", $adminInfo['id'], $adminInfo['username'], json_encode(['错误API' => retMAC(), 'error' => $e->getMessage(), '操作用户IP' => get_ip()]));
            rLog(['operate' => 'sql错误', 'error' => $e->getMessage()]);
            ret(404, '服务器异常请联系管理员');
        }
    }

    /**
     * 修改密码
     * @param Request $request
     */
    public function modifyPw(Request $request)
    {
        try {
            //赋值
            $new_password = input('post.new_password', '', 'trim');
            $repeat_password = input('post.repeat_password', '', 'trim');
            $new_password != $repeat_password ? ret(400, '两次新密码不一致！') : '';
            $data['token'] = randomStr(64, 3) . $request->adminInfo['id'];
            $data['password'] = password_hash($new_password, PASSWORD_DEFAULT);
            if (adminM::where('id', $request->adminInfo['id'])->update($data)) {
                comm::oplog("修改密码", $request->adminInfo['id'], $request->adminInfo['username'], "密码修改成功，" . "新密码:" . $new_password . " | 操作用户IP:" . get_ip());
                ret(200, '成功');
            }
        } catch (\Exception $e) {
            comm::oplog("sql错误", $request->adminInfo['id'], $request->adminInfo['username'], json_encode(['错误API' => retMAC(), 'error' => $e->getMessage(), '操作用户IP' => get_ip()]));
            rLog(['operate' => 'sql错误', 'error' => $e->getMessage()]);
            ret(404, '服务器异常请联系管理员');
        }
    }

    /**
     * 删除管理员
     * @param Request $request
     * by J.sky
     * 2020年5月5日11:54:05
     */
    public function del(Request $request)
    {
        try {
            //获取管理员信息
            $adminInfo = $request->adminInfo;
            //逻辑判断
            $ret = adminM::where('id', input('post.id', '', 'trim'))->field('id,username,group_id')->find();
            $ret ? '' : ret(400, '需要删除的账户不存在！');
            $ret['group_id'] == 1 ? ret(400, '权限不足，无法删除！') : "";
            if (adminM::where('id', $ret['id'])->delete()) {
                comm::oplog("删除管理员", $adminInfo['id'], $adminInfo['username'], "删除账户ID:" . $ret['id'] . " | 删除账户:" . $ret['username'] . " | 操作用户IP:" . get_ip());
                ret(200, '成功');
            }
            ret(400, '操作失败');
        } catch (\Exception $e) {
            comm::oplog("sql错误", $adminInfo['id'], $adminInfo['username'], json_encode(['错误API' => retMAC(), 'error' => $e->getMessage(), '操作用户IP' => get_ip()]));
            rLog(['operate' => 'sql错误', 'error' => $e->getMessage()]);
            ret(404, '服务器异常请联系管理员');
        }
    }

    /**
     * 管理员列表
     * @param Request $request
     * @return $this
     */
    public function adminList(Request $request){
        try {
            $adminInfo = $request->adminInfo;

            $limit = input('post.limit',15,'trim');
            $where = [];
            if(!empty(input('post.str'))){
                $str = input('post.str','','trim');
                $where[] = ['username|nike','like','%'.$str.'%'];
            }
            $where[] = ['group_id','<>','1'];
            $listObj = DB::name('admin')->where($where)->alias('a')->leftJoin([
                ['group b', 'a.group_id=b.id'],
            ])->field('a.id,a.username,a.nike,a.out_time,a.group_id,b.name group_name')->order('id', 'desc')->paginate($limit);
            return ret(200, '成功', ["data"=>$listObj->toArray()['data'],"total"=>$listObj->toArray()['total']]);
        } catch (\Exception $e) {
            comm::oplog("sql错误",$adminInfo['id'],$adminInfo['username'],json_encode(['错误API'=>retMAC(),'error' => $e->getMessage(),'操作用户IP'=>get_ip()]));
            rLog(['operate' => 'sql错误', 'error' => $e->getMessage()]);
            ret(404, '服务器异常请联系管理员');
        }
    }

    /**
     * 修改管理员
     * @param Request $request
     */
    public function modifyAdmin(Request $request)
    {
        try {
            $id = input('post.id', '', 'trim');
            empty($id) ?  ret(400, '请选择需要修改的账号！') : '';
            $id == 1 ? ret(400, '权限不足无法修改！') : '';
            $data['username'] = input('post.username', '', 'trim');
            empty($data['username']) ?  ret(400, '请填写账户！') : '';
            $data['nike'] = empty(input('post.nike', '', 'trim')) ? $data['username'] : input('post.nike', '', 'trim');
            $pwd = input('post.password', '', 'trim');
            if(!empty($pwd)){
                $data['password'] = password_hash($pwd, PASSWORD_DEFAULT);
            }
            $g_id = input('post.group_id', '', 'trim');
            empty($g_id) ?  ret(400, '请选择所属分组！') : '';
            $data['group_id']= $g_id;
            if (adminM::where('id', $id)->update($data)) {
                ret(200, '成功');
            }
            ret(400, '修改失败');
        } catch (\Exception $e) {
            comm::oplog("sql错误",$request->adminInfo['id'],$request->adminInfo['username'],json_encode(['错误API'=>retMAC(),'error' => $e->getMessage(),'操作用户IP'=>get_ip()]));
            rLog(['operate' => 'sql错误', 'error' => $e->getMessage()]);
            ret(404, '服务器异常请联系管理员');
        }
    }
}
